<template>
  <div class="article-edit">
    <!-- 编辑弹窗 -->
    <cvue-dialog
      :dialogVisible="dialogVisible"
      :title="title"
      :dialogLoading="dialogLoading"
      :isFullscreen="true"
      dialogWidth="600px"
      @handleOpen="getDetail"
      @closeDialog="closeDialog"
      @confirmDialog="confirmDialog"
      @handleClose="handleClose">
      <div class="dialog-body dialog-product" slot="dialogBody">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input v-model="ruleForm.title" :disabled="disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="分类" prop="cid">
                <el-cascader 
                  v-model="ruleForm.cid" 
                  :options="$parent.categoryOptions" 
                  style="width:100%"
                  :show-all-levels="false"
                  clearable
                  :props="$parent.treeProp"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="摘要" prop="description">
                <el-input v-model="ruleForm.description" :disabled="disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="标签" prop="tags">
                <el-input v-model="ruleForm.tags" :disabled="disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="外链" prop="link">
                <el-input v-model="ruleForm.link" :disabled="disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="排序号" prop="sort">
                <el-input v-model="ruleForm.sort" :disabled="disabled" type="number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                  <el-radio :label="0">草稿</el-radio>
                  <el-radio :label="1">发布</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="图片" prop="avatar">
                <cvue-upload 
                  cssClass="avatar-uploader"
                  :fileParams="fileParams"
                  :fileLoading="fileLoading"
                  @success="handleAvatarSuccess"
                  :actionUrl="baseServer+'/v1/api/uploadImg'">
                  <template>
                    <img v-if="imageUrl" :src="baseServer + imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </template>
                </cvue-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容" prop="content">
                <div class="edit-wrap">
                  <quill-editor
                    ref="myQuillEditor"
                    v-model="ruleForm.content"
                    class="quill-editor"
                    :options="editorOption"
                    @change="onEditorChange($event)"
                    @blur="onEditorBlur($event)"
                    @focus="onEditorFocus($event)"
                    @ready="onEditorReady($event)"/>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </cvue-dialog>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import cvueDialog from '@/components/cvue-dialog'
import { validPhone, validIp } from '@/util/validator.js'
import cvueUpload from '@/components/cvue-upload'
import {baseServer} from '@/config/config'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'article-edit',
  components: {
    cvueDialog,
    cvueUpload,
    quillEditor
  },
  data () {
    return {
      ruleForm: {
        title: '',
        cid: [],
        description: '',
        tags: '',
        sort: 0,
        status: 1,
        avatar: '',
        content: '',
        link: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        cid: [
          { required: true, message: '请选择分类', trigger: 'blur' }        
        ],
        tags: [
          { required: true, message: '请输入标签', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }   
        ]
      },
      disabled: false,
      dialogLoading: false,
      imageUrl: '',
      fileLoading: false,
      baseServer: baseServer,
      shopArr: [],
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'color': [] }],
            [{ 'align': [] }],
            ['image']
          ]
        },
        placeholder: '请输入'
      },
      cateList: []
    }
  },
  mounted () {
    this.getCategorys()
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    title () {
      var title = ''
      if (this.$parent.actionType == 'add') {
        title = '新增'
      } else {
        title = '编辑'
      }
      return title
    },
    fileParams () {
      return {
        'access_token': this.token
      }
    },
    ...mapGetters(['token', 'userInfo'])
  },
  methods: {
    // 列表接口
    getCategorys () {
      var params = {
        status: 1
      }
      this.$store.dispatch('blog/BlogCategoryGet', params).then(res => {
        if (res.code == 200) {
          // console.log(res)
          this.cateList = res.data
          this.getEditDetail()
        }
      }).catch(err => {
        this.$message({type: 'error', message: err.msg})
      })
    },
    getShop (name) {
      var params = {
        page: 1,
        limit: 10,
        name: ''
      }
      this.$store.dispatch('shop/ShopGet', params).then(res => {
        // console.log(res)
        var data = res.data.datas
        this.shopArr = data
      }).catch(err => {
        console.log(err)
      })
    },
    onEditorBlur (quill) {
      // console.log('editor blur!', quill)
    },
    onEditorFocus (quill) {
      // console.log('editor focus!', quill)
    },
    onEditorReady (quill) {
      // console.log('editor ready!', quill)
    },
    onEditorChange ({ quill, html, text }) {
      // console.log('editor change!', quill, html, text)
      // this.ruleForm.TipContent = html
    },
    // 触发事件
    handleClose () {
      this.$emit('handleClose')
    },
    closeDialog () {
      this.$emit('closeDialog')
    },
    confirmDialog () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var params = {
            id: this.$parent.actionType == 'add' ? '' : this.$parent.rowData.id,
            title: this.ruleForm.title,
            category_id: this.ruleForm.cid[this.ruleForm.cid.length - 1],
            description: this.ruleForm.description,
            tags: this.ruleForm.tags,
            sort: this.ruleForm.sort,
            status: this.ruleForm.status,
            cover: this.imageUrl,
            content: this.ruleForm.content,
            author_id: this.userInfo.id,
            link: this.ruleForm.link
          }
          // console.log(params)
          this.dialogLoading = true
          var url = this.$parent.actionType == 'add' ? 'blog/ArticlePost' : 'blog/ArticlePut'
          this.$store.dispatch(url, params).then(res => {
            // console.log(res)
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'success'
              })
              this.$emit('confirmDialog')
            }
            this.dialogLoading = false
          }).catch(err => {
            this.dialogLoading = false
            this.$message({message: err.msg, duration: 2000, type: 'error'})
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getDetail () {
    },
    getMenuIds (menuList, id) {
      var arr = [id]
      for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].id == id) {
          arr.unshift(menuList[i].pid)
          this.getMenuIds(menuList, menuList[i].pid)
        }
      }
      return arr
    },
    getEditDetail () {
      if (this.$parent.actionType == 'edit') {
        // console.log(this.$parent.rowData)
        this.$set(this.ruleForm, 'title', this.$parent.rowData.title)
        var cIds = this.getMenuIds(this.cateList, this.$parent.rowData.category_id)
        cIds.shift()
        this.$set(this.ruleForm, 'cid', cIds)
        this.$set(this.ruleForm, 'description', this.$parent.rowData.description)
        this.$set(this.ruleForm, 'tags', this.$parent.rowData.tags)
        this.$set(this.ruleForm, 'sort', this.$parent.rowData.sort)
        this.$set(this.ruleForm, 'status', this.$parent.rowData.status)
        this.$set(this.ruleForm, 'content', this.$parent.rowData.content)
        this.$set(this.ruleForm, 'link', this.$parent.rowData.link)
        this.imageUrl = this.$parent.rowData.cover
      }
    },
    handleAvatarSuccess ({response, file, fileList}) {
      // console.log(response)
      this.imageUrl = response.data.filePath
    }
  }
}
</script>
<style lang="scss">
.article-edit{
  .dialog-product{
    height: calc(100vh - 180px);
    padding: 20px 300px!important;
    margin: 0 auto;
    overflow: auto;
  }
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
  }
  .avatar {
    width: 130px;
    height: 130px;
    display: block;
  }
  .edit-wrap{
    height: 510px;
    .ql-snow .ql-picker{
      line-height: 24px;
    }
    .ql-container{
      white-space:pre-wrap;
    }
  }
  .quill-editor{
    width: 100%;
    height: 460px;
  }
}
</style>
